import threading
import queue
import time
import random

# 创建一个队列
q = queue.Queue()


# 生产者线程函数
def producer(id):
    for i in range(10):
        item = random.randint(1, 100)  # 生成一个随机数
        q.put(item)  # 将数据放入队列
        print(f"生产者 {id} 生产了: {item}")
        time.sleep(random.random())  # 随机休眠一段时间


# 消费者线程函数
def consumer(id):
    while True:
        item = q.get()  # 从队列中取出数据
        if item is None:
            q.task_done()  # 标记任务完成
            break  # 如果取到 None，表示生产者已经完成
        print(f"消费者 {id} 消费了: {item}")
        time.sleep(random.random())  # 随机休眠一段时间
        q.task_done()  # 标记任务完成


# 创建多个生产者和消费者线程
num_producers = 3
num_consumers = 2

producer_threads = []
consumer_threads = []

# 启动生产者线程
for i in range(num_producers):
    thread = threading.Thread(target=producer, args=(i,))
    producer_threads.append(thread)
    thread.start()

# # 启动消费者线程
# for i in range(num_consumers):
#     thread = threading.Thread(target=consumer, args=(i,))
#     consumer_threads.append(thread)
#     thread.start()


# # 等待所有生产者线程完成
# for thread in producer_threads:
#     thread.join()

# # 生产者完成后，向队列中放入多个 None，通知所有消费者结束
# for _ in range(num_consumers):
#     q.put(None)

# # 等待所有消费者线程完成
# for thread in consumer_threads:
#     thread.join()

for i in range(100):
    print(f"主线程循环 {i}")
print("所有任务已完成")
